#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use Getopt::Long;
#use Data::Dump qw(dump);

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

my $usage = <<'USAGE';

USAGE:

    re_replace_lookup.pl
                --from_regex "(ENST\d+)"
                --lookup_file file
                --keep_non_matching_lines
                [--iterative]
                [--verbose]
                [--help]

    Iterates through files and filters each line according to the supplied
        regular expression

	Prints to STDOUT
	
USAGE


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory
my $lookup_file;
my $from_regex;
my $keep_non_matching_lines;
my $verbose;
my $iterative;
# optional parameters
my $help;
GetOptions(
			'verbose'			=> \$verbose,
			'iterative'			=> \$iterative,
			'lookup_file=s'		=> \$lookup_file,
			'from_regex=s'		=> \$from_regex,
			'keep_non_matching_lines'	=> \$keep_non_matching_lines,
			'help'				=> \$help);

die $usage if ($help);
die $usage unless ($from_regex && $lookup_file);
my %lookup;
{
	open LOOKUP_FILE, $lookup_file or die "Error!\nCould not open $lookup_file\n$!\n";
	for (<LOOKUP_FILE>)
	{
		chomp;
		next unless /([^\t]+)\t(.+)/;
		$lookup{$1} = $2;
	}
}
for (@ARGV)
{
	die "Error:\n\t$_ does not exists.\n" unless -f $_;
}
my $cnt_replaced = 0;

my $cmd = <<"CMD";
	for my \$line(<>)
	{
		if#OR_WHILE
		(\$line =~ /($from_regex)/g)
		{
			my \$found = \$1;
			my \$len = length(\$found);
			my \$pos = pos(\$line) - length(\$found);
			if (exists \$lookup{\$found})
			{
				my \$to = \$lookup{\$found};
				\$line = substr(\$line, 0, \$pos).\$to.substr(\$line, \$pos + \$len);
				\$cnt_replaced++;
				#PRINT_FIND;
			}
		}
		#PRINT_KEEP;
	}
CMD

	if ($keep_non_matching_lines)
	{
		$cmd =~ s/#PRINT_KEEP/print \$line/;
	}
	else
	{
		$cmd =~ s/#PRINT_FIND/print \$line/;
	}
	if ($iterative)
	{
		$cmd =~ s/if#OR_WHILE/while/;
	}
	#print STDERR dump(%lookup);
	#print STDERR $cmd;
	eval $cmd;


if ($verbose)
{
	print STDERR "\t$cnt_replaced\tmatches replaced.\n";
}
